<template>
  <div v-if="visible" class="modal-overlay" @click="handleOverlayClick">
    <div class="modal">
      <div class="modal-header">
        <div class="modal-title">
          <span>手动创建项目</span>
        </div>
        <button class="close-btn" @click="closeModal">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="modal-content">
        <form @submit.prevent="handleSave">
          <div class="form-grid">
            <!-- 客户名称 -->
            <div class="form-group">
              <label class="form-label">
                客户名称 <span class="required">*</span>
              </label>
              <input type="text" class="form-input" v-model="formData.customer_name" required placeholder="请输入客户名称">
            </div>

            <!-- 客户域名 -->
            <div class="form-group">
              <label class="form-label">
                客户域名 <span class="required">*</span>
              </label>
              <input type="text" class="form-input" v-model="formData.customer_domain" required placeholder="请输入客户域名">
            </div>

            <!-- 项目类型 -->
            <div class="form-group">
              <label class="form-label">
                项目类型 <span class="required">*</span>
              </label>
              <select class="form-select" v-model="formData.project_type" required>
                <option value="BACKLINK">手动外链</option>
                <option value="SEO">SEO</option>
              </select>
            </div>

            <!-- 项目状态 -->
            <div class="form-group">
              <label class="form-label">项目状态</label>
              <select class="form-select" v-model="formData.status">
                <option value="未开始">未开始</option>
                <option value="未达标">未达标</option>
                <option value="已达标">已达标</option>
              </select>
            </div>

            <!-- 客户经理 -->
            <div class="form-group">
              <label class="form-label">客户经理</label>
              <input type="text" class="form-input" v-model="formData.customer_manager" placeholder="请输入客户经理">
            </div>

            <!-- 合同金额 -->
            <div class="form-group">
              <label class="form-label">
                合同金额 <span class="required">*</span>
              </label>
              <input type="number" class="form-input" v-model.number="formData.contract_amount" required
                placeholder="请输入合同金额" min="0" step="0.01">
            </div>


            <!-- 开始日期 -->
            <div class="form-group">
              <label class="form-label">开始日期</label>
              <input type="date" class="form-input" v-model="formData.start_date">
            </div>

            <!-- 结束日期 -->
            <div class="form-group">
              <label class="form-label">结束日期</label>
              <input type="date" class="form-input" v-model="formData.end_date">
            </div>

            <!-- 合同条款详情 -->
            <div class="form-group full-width">
              <label class="form-label">合同条款详情 (注：填写原合同未解析数据)</label>
              <div class="contract-terms-form">
                <div class="form-row">
                  <div class="form-group">
                    <label class="form-label">合同概要</label>
                    <input type="text" class="form-input" v-model="formData.contract_terms.text"
                      placeholder="如：综合外链(2400)|PR通稿(600)">
                  </div>
                </div>
                <div class="form-row">
                  <div class="form-group">
                    <label class="form-label">备注说明</label>
                    <textarea class="form-textarea" v-model="formData.contract_terms.extra_note"
                      placeholder="如：PR通稿(DA大于15不少于50条)|综合外链(DA大于45不少于50条)" rows="2"></textarea>
                  </div>
                </div>
              </div>
            </div>

            <!-- 合同要求条目 -->
            <div class="form-group full-width">
              <div class="requirements-header">
                <label class="form-label">合同要求条目</label>
                <button type="button" class="btn-add-requirement" @click="addRequirement">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="12" y1="5" x2="12" y2="19"></line>
                    <line x1="5" y1="12" x2="19" y2="12"></line>
                  </svg>
                  添加条目
                </button>
              </div>

              <div class="requirements-list">
                <div v-if="formData.contract_requirements.length === 0" class="no-requirements">
                  暂无条目，点击"添加条目"按钮添加合同要求
                </div>

                <div v-for="(requirement, index) in formData.contract_requirements" :key="index"
                  class="requirement-form">
                  <div class="requirement-header">
                    <span class="requirement-index">条目 {{ index + 1 }}</span>
                    <button type="button" class="btn-remove" @click="removeRequirement(index)">
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                        stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                      </svg>
                    </button>
                  </div>

                  <div class="requirement-fields">
                    <div class="form-row">
                      <div class="form-group">
                        <label class="form-label">要求类型 <span class="required">*</span></label>
                        <!-- <select class="form-select" v-model="requirement.requirement_type" required>
                          <option value="">请选择要求类型</option>
                          <option value="综合外链">综合外链</option>
                          <option value="PR通稿">PR通稿</option>
                          <option value="新闻发布">新闻发布</option>
                          <option value="软文推广">软文推广</option>
                          <option value="其他">其他</option>
                        </select> -->
                        <input type="text" class="form-input" v-model="requirement.requirement_type" required
                          placeholder="如：综合外链/PR通稿/UGC外链/维基外链/...">
                      </div>
                      <div class="form-group">
                        <label class="form-label">目标数量 <span class="required">*</span></label>
                        <input type="number" class="form-input" v-model.number="requirement.target_quantity"
                          placeholder="如：2400" min="1" required>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="form-group">
                        <label class="form-label">DA要求</label>
                        <input type="number" class="form-input" v-model.number="requirement.quality_requirements.da"
                          placeholder="如：15" min="0" max="100">
                      </div>
                      <div class="form-group">
                        <label class="form-label">质量数量要求</label>
                        <input type="number" class="form-input" v-model.number="requirement.quality_requirements.count"
                          placeholder="如：50" min="1">
                      </div>
                      <div class="form-group">
                        <label class="form-label">链接类型</label>
                        <select class="form-select" v-model="requirement.quality_requirements.dofollow">
                          <option :value="null">不限制</option>
                          <option :value="true">Dofollow</option>
                          <option :value="false">Nofollow</option>
                        </select>
                      </div>
                    </div>

                    <div class="form-row">
                      <div class="form-group">
                        <label class="form-label">附加说明</label>
                        <textarea class="form-textarea" v-model="requirement.additional_notes" placeholder="请输入附加说明..."
                          rows="2"></textarea>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>

      <div class="modal-actions">
        <button class="btn btn-secondary" @click="closeModal">
          取消
        </button>
        <button class="btn btn-primary" @click="handleSave">
          创建项目
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { Project } from '../types'
import { projectsApi, ProjectFormData } from '../api/services/projects'

interface Props {
  visible: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'create': [project: Omit<Project, 'id' | 'created_time' | 'updated_time'>]
}>()

const formData = ref<Omit<ProjectFormData, 'id' | 'created_time' | 'updated_time'>>({
  project_code: '',
  customer_name: '',
  customer_domain: '',
  project_type: 'BACKLINK',
  status: '未开始',
  contract_terms: {
    img: null,
    text: '',
    extra_note: '',
    amount: undefined
  },
  start_date: null,
  end_date: null,
  customer_manager: null,
  contract_amount: undefined,
  contract_requirements: []
})

// 重置表单数据
const resetForm = () => {
  formData.value = {
    project_code: '',
    customer_name: '',
    customer_domain: '',
    project_type: 'BACKLINK',
    status: '未开始',
    contract_terms: {
      img: null,
      text: '',
      extra_note: '',
      amount: undefined
    },
    start_date: null,
    end_date: null,
    customer_manager: null,
    contract_amount: undefined,
    contract_requirements: []
  }
}

// 监听弹窗显示状态，重置表单
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    resetForm()
  }
})

const closeModal = () => {
  emit('update:visible', false)
}

const handleOverlayClick = (e: Event) => {
  if (e.target === e.currentTarget) {
    closeModal()
  }
}

// 添加合同要求条目
const addRequirement = () => {
  formData.value.contract_requirements?.push({
    requirement_type: '',
    target_quantity: 0,
    quality_requirements: {
      as: null,
      da: null,
      count: null,
      dofollow: null
    },
    additional_notes: '',
    status: 'PENDING',
  })
}

// 删除合同要求条目
const removeRequirement = (index: number) => {
  formData.value.contract_requirements?.splice(index, 1)
}

const handleSave = async () => {
  // 验证必填字段
  if (!formData.value.customer_name || !formData.value.customer_domain || !formData.value.project_type ||
    !formData.value.contract_amount) {
    alert('请填写所有必填字段')
    return
  }

  // 验证合同要求条目
  if (formData.value.contract_requirements && formData.value.contract_requirements.length > 0) {
    for (let i = 0; i < formData.value.contract_requirements.length; i++) {
      const req = formData.value.contract_requirements[i]
      if (!req.requirement_type || !req.target_quantity) {
        alert(`请完善第 ${i + 1} 个合同要求条目的必填信息`)
        return
      }
    }
  }

  // 验证日期逻辑
  if (formData.value.start_date && formData.value.end_date) {
    if (new Date(formData.value.start_date) > new Date(formData.value.end_date)) {
      alert('开始日期不能晚于结束日期')
      return
    }
  }

  // 同步合同金额到contract_terms
  if (formData.value.contract_amount) {
    formData.value.contract_terms.amount = formData.value.contract_amount
  }

  try {
    // 准备API数据
    let startDateYearMonth = ''
    if (formData.value.start_date) {
      const date = new Date(formData.value.start_date)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      startDateYearMonth = `${year}${month}`
    }


    const apiData: ProjectFormData = {
      project_code: `${formData.value.project_type}-${formData.value.customer_name}-${formData.value.customer_domain}-${startDateYearMonth}`,
      customer_name: formData.value.customer_name,
      customer_domain: formData.value.customer_domain,
      project_type: formData.value.project_type,
      status: formData.value.status,
      contract_terms: formData.value.contract_terms,
      start_date: formData.value.start_date,
      end_date: formData.value.end_date,
      customer_manager: formData.value.customer_manager,
      contract_requirements: formData.value.contract_requirements || []
    }

    console.log('创建项目数据:', apiData)

    // 调用API创建项目
    const response = await projectsApi.create(apiData)

    // 触发父组件的创建事件
    emit('create', response.data)
    closeModal()

  } catch (error) {
    console.error('创建项目失败:', error)
    alert('创建项目失败，请检查网络连接或联系管理员')
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  box-shadow: 0 25px 50px rgba(0, 0, 0, 0.25);
}

.modal-header {
  padding: 24px 30px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f9fafb;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  color: #6b7280;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #374151;
}

.modal-content {
  padding: 30px;
  max-height: 60vh;
  overflow-y: auto;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 6px;
}

.required {
  color: #ef4444;
}

.form-input,
.form-select,
.form-textarea {
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: #6366f1;
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.modal-actions {
  padding: 20px 30px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  background: #f9fafb;
}

.btn {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
}

.btn-secondary {
  background: white;
  color: #374151;
  border-color: #d1d5db;
}

.btn-secondary:hover {
  background: #f9fafb;
}

.btn-primary {
  background: #6366f1;
  color: white;
}

.btn-primary:hover {
  background: #5b21b6;
}

/* 合同条款表单样式 */
.contract-terms-form {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  padding: 16px;
  background: #f9fafb;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  margin-bottom: 16px;
}

.form-row:last-child {
  margin-bottom: 0;
}

/* 合同要求条目样式 */
.requirements-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.btn-add-requirement {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #6366f1;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-add-requirement:hover {
  background: #5b21b6;
}

.requirements-list {
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: #f9fafb;
  min-height: 60px;
}

.no-requirements {
  padding: 20px;
  text-align: center;
  color: #6b7280;
  font-style: italic;
}

.requirement-form {
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin: 8px;
  overflow: hidden;
}

.requirement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f3f4f6;
  border-bottom: 1px solid #e5e7eb;
}

.requirement-index {
  font-weight: 600;
  font-size: 14px;
  color: #374151;
}

.btn-remove {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-remove:hover {
  background: #dc2626;
}

.requirement-fields {
  padding: 16px;
}

.requirement-fields .form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.requirement-fields .form-row:last-child {
  grid-template-columns: 1fr;
}

.requirement-fields .form-row:nth-child(2) {
  grid-template-columns: 1fr 1fr 1fr;
}

@media (max-width: 768px) {
  .modal {
    width: 95%;
    margin: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
  }

  .modal-actions {
    flex-direction: column;
  }

  .requirements-header {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .requirement-fields .form-row {
    grid-template-columns: 1fr;
  }

  .requirement-fields .form-row:nth-child(2) {
    grid-template-columns: 1fr;
  }
}
</style>